import {ref} from 'vue';
import {ElMessage} from 'element-plus';
import {vueRouter} from './my-vue-router'
import {defineStore} from "pinia";


// 使用pinia存放登录信息
export const useLoginStore = defineStore('loginStore', () => {
    const userId = ref(0)
    const username = ref('')
    const nickname = ref('')
    // 角色 {RoleCode:RoleName...}
    const roles = ref<{ [key: string]: string }>({})
    // 可使用的角色，用于用户切换角色
    const availableRoles = ref<{ [key: string]: string }>({})
    // 权限 PermissionCode
    const permissions = ref<Array<string>>([])

    // 设置
    function set(data: any) {
        userId.value = data.userId
        username.value = data.username
        nickname.value = data.nickname
        permissions.value = data.permissions
        roles.value = data.roles
        availableRoles.value = data.availableRoles
    }

    function $reset() {
        userId.value = 0
        username.value = ''
        nickname.value = ''
        permissions.value = []
        roles.value = {}
        availableRoles.value = {}
    }

    // 打包返回
    return {userId, username, nickname, roles, permissions, availableRoles, set, $reset}
}, {
    persist: {
        enabled: true,
    }
})


// 完成登录后的操作
export function afterLogin(nickname: string) {
    // 提示
    ElMessage.success("欢迎回来，" + nickname)
    // 页面跳转
    vueRouter.push("/")
}
